package com.gs.douban.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class HttpClientUtil {
	static HttpClient hc = new HttpClient();
	static {
		hc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
	}

	public String get(String url) throws HttpException, IOException {
		clearCookies();
		GetMethod g = new GetMethod(url);
		hc.executeMethod(g);
		return g.getResponseBodyAsString();
	}
	
	public String get(String url, Set<Header> headers) throws HttpException, IOException {
		clearCookies();
		GetMethod g = new GetMethod(url);
		for (Header header : headers) {
			g.addRequestHeader(header);
		}
		hc.executeMethod(g);
		return g.getResponseBodyAsString();
	}
	
	public String get(String url, String cookies) throws HttpException,
			IOException {
		clearCookies();
		GetMethod g = new GetMethod(url);
		g.setFollowRedirects(false);
		if (!cookies.equals("")) {
			g.setRequestHeader("cookie", cookies);
		}
		hc.executeMethod(g);
		return g.getResponseBodyAsString();
	}
	
	public String getHeader(String url, String cookies,String headername) throws HttpException, IOException{
		clearCookies();
		GetMethod g = new GetMethod(url);
		g.setFollowRedirects(false);
		if (!cookies.equals("")) {
			g.setRequestHeader("cookie", cookies);
		}
		hc.executeMethod(g);
		return g.getResponseHeader(headername) == null ? null :g.getResponseHeader(headername).getValue();
	}
	
	public String post(String postURL, Map<String, String> partam, String cookies)
			throws HttpException, IOException {
		clearCookies();
		PostMethod p = new PostMethod(postURL);
		for (String key : partam.keySet()) {
			if (partam.get(key) != null) {
				p.setParameter(key, partam.get(key));
			}
		}
		if (!cookies.equals("")) {
			p.setRequestHeader("cookie", cookies);
		}
		hc.executeMethod(p);
		return p.getResponseBodyAsString();
	}

	public String getCookie() {
		Cookie[] cookies = hc.getState().getCookies();
		String tmpcookies = "";
		for (Cookie c : cookies) {
			tmpcookies += c.toString() + ";";
		}
		return tmpcookies;
	}
	
	public void clearCookies(){
		hc.getState().clearCookies();
	}
	
}
